package test.study.java.jol.samples;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;

@Slf4j
public class JOLSample_12_BiasedLocking {
    /*
     * This is a dive into the mark word.
     *
     * Among other things, mark words store locking information.
     * We can clearly see how the mark word contents change when
     * we acquire the lock, and subsequently release it.
     *
     * In this example, we demonstrate biased locking. Every Java
     * _3_object is potentially a target for synchronization. Most of
     * the time, the _3_object is ever locked by a single thread. In
     * this case, we can "bias" the _3_object to that single thread,
     * and make the synchronization on it very cheap.
     *
     * To demonstrate this, we print the _3_object internals before/during/after
     * lock acquisition. You can notice that mark word changes from
     * "biasable" to "biased". The mark word is left the same after
     * unlock: the _3_object is now biased towards the thread.
     *
     * Prior to JDK 9, biased locking is only enabled after 5 seconds
     * after the VM startup. Therefore, the test is best run with
     * -XX:BiasedLockingStartupDelay=0 on JDK 8 and lower. After JDK 15,
     * biased locking is disabled by default, and this tests needs
     * -XX:+UseBiasedLocking.
     */

    public static void main(String[] args) {
        log.info(VM.current().details());

        final A a = new A();

        ClassLayout layout = ClassLayout.parseInstance(a);

        log.info("**** Fresh _3_object");
        log.info(layout.toPrintable());

        synchronized (a) {
            log.info("**** With the lock");
            log.info(layout.toPrintable());
        }

        log.info("**** After the lock");
        log.info(layout.toPrintable());
    }

    public static class A {
        // no fields
    }
}
